<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区-->
    <el-card class="box-card">
      <!-- 添加对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="addUserDialog"
        width="50%"
        @close="$refs.addFormRef.resetFields()"
      >
        <el-form :rules="addFormRules" ref="addFormRef" :model="addForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="editorUserDialog"
        width="50%"
        @close="$refs.editorFormRef.resetFields()"
      >
        <el-form
          :rules="editorFormRules"
          ref="editorFormRef"
          :model="editorForm"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editorForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="editorForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editorForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editorUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="editorUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- //分配角色 -->
      <el-dialog
        title="用户分配角色"
        :visible.sync="setUserDialog"
        width="50%"
        @close="$refs.setFormRef.resetFields()"
      >
        <el-form :rules="setFormRules" ref="setFormRef" :model="setForm" label-width="120px">
          <el-form-item label="当前的用户：" prop="username">{{setForm.username}}</el-form-item>
          <el-form-item label="当前的角色：" prop="role_name">{{setForm.role_name}}</el-form-item>
          <el-form-item label="分配新角色 " prop="rid">
            <el-select v-model="setForm.rid" clearable placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="fenRole()">确 定</el-button>
        </span>
      </el-dialog>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="querycdt.query"
            placeholder="请输入搜索内容"
            class="input-with-select"
            clearable
            @clear="getUserlist()"
            @keyup.enter.native="getUserlist()"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserlist()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="addUserDialog = true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userlist" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="mobile" label="手机号" width="160"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="130"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="160"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="80">
          <el-switch
            v-model="info.row.mg_state"
            slot-scope="info"
            @change="statusChange(info.row,info.row.mg_state)"
          ></el-switch>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="info">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditorUserDialog(info.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(info.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRuleDialog(info.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querycdt.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="querycdt.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tot"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  created () {
    this.getUserlist()
  },
  methods: {
    async getUserlist () {
      const { data: dt } = await this.$http.get('users', {
        params: this.querycdt
      })
      console.log(dt)
      this.tot = dt.data.total
      this.userlist = dt.data.users
    },
    /**  数据分页相关1 */
    // 每条记录条数变化的回调处理
    handleSizeChange (arg) {
      // arg: 变化后的记录条数
      // console.log(arg)
      this.querycdt.pagesize = arg
      // 重新根据条件获得数据
      this.getUserlist()
    },
    // 当前页码变化的回调处理
    handleCurrentChange (arg) {
      // arg: 变化后的当前页码值
      // console.log(arg)
      this.querycdt.pagenum = arg
      // 根据变化后的页码重新获得数据
      this.getUserlist()
    },
    /** 添加用户 */
    addUser () {
      var that = this
      this.$refs.addFormRef.validate(async valid => {
        // valid===true 校验ok
        // valid===false 校验失败
        if (valid) {
          // 把用户名和密码交给axios，之后去服务器端做真实性校验
          // var {data:dt} 对象结构赋值重命名操作
          var { data: res } = await that.$http.post('users', this.addForm)

          // 登录失败判断
          if (res.meta.status !== 201) {
            return that.$message.error(res.meta.msg)
          }
          that.$message.success(res.meta.msg)
          that.addUserDialog = false
          that.getUserlist()
        }
      })
    },
    /* 删除用户 */
    delUser (ids) {
      this.$confirm('确定要删除该用户么?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // axios调用api删除数据
          const { data: res } = await this.$http.delete('/users/' + ids)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          }
          // 删除成功提醒
          this.$message.success(res.meta.msg)
          this.getUserlist()
        })
        .catch(() => {})
    },
    // 修改用户信息
    editorUser () {
      var that = this
      console.log(this.editorForm)
      this.$refs.editorFormRef.validate(async valid => {
        // valid===true 校验ok
        // valid===false 校验失败
        if (valid) {
          // 把用户名和密码交给axios，之后去服务器端做真实性校验
          var { data: res } = await that.$http.put(
            '/users/' + this.editorForm.id,
            this.editorForm
          )
          // 登录失败判断
          if (res.meta.status !== 200) {
            return that.$message.error(res.meta.msg)
          }
          that.$message.success(res.meta.msg)
          that.editorUserDialog = false
          that.getUserlist()
        }
      })
    },

    async showEditorUserDialog (ids) {
      // 显示编辑对话框
      this.editorUserDialog = true
      const { data: res } = await this.$http.get('/users/' + ids)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editorForm = res.data
    },
    async statusChange (user, state) {
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${state}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 显示分配角色对话框
    async showSetRuleDialog (user) {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.roleList = res.data
      this.setForm = user
      this.setUserDialog = true
    },
    fenRole () {
      var that = this
      console.log(this.setForm)
      this.$refs.setFormRef.validate(async valid => {
        // valid===true 校验ok
        // valid===false 校验失败
        if (valid) {
          // 把用户名和密码交给axios，之后去服务器端做真实性校验
          var { data: res } = await that.$http.put(
            `users/${this.setForm.id}/role`,
            { rid: this.setForm.rid }
          )
          // 登录失败判断
          if (res.meta.status !== 200) {
            return that.$message.error(res.meta.msg)
          }
          that.$message.success(res.meta.msg)
          that.setUserDialog = false
          that.getUserlist()
        }
      })
    }
  },
  data () {
    var checkMobile = (rule, value, callback) => {
      var reg = /^1[3-9]\d{9}$/
      if (!reg.test(value)) {
        return callback(new Error('手机号格式不正确'))
      }
      callback()
    }
    var checkEmail = (rule, value, callback) => {
      var reg = /^\w+@\w+(\.[a-z]+)+$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式不正确'))
      }
      callback()
    }
    return {
      addFormRules: {
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        password: [{ required: true, message: '密码必填', trigger: 'blur' }],
        mobile: [
          { required: true, message: '手机号码必填', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editorFormRules: {
        // username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        mobile: [
          // { required: true, message: '手机号码必填', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱必填', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      editorForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      setFormRules: {
        rid: [
          { required: true, message: '必须选取一个角色', trigger: 'change' }
        ]
      },
      roleList: [],
      setUserDialog: false,
      setForm: {
        id: '',
        username: '',
        role_name: '',
        rid: 0
      },
      addUserDialog: false,
      editorUserDialog: false,
      tot: 0,
      userlist: [],
      querycdt: {
        query: '', // 搜索关键字
        pagenum: 1, // 当前页码
        pagesize: 3 // 每页显示数据条数
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
